const userModel = require('../models/userModel')
const bcrypt = require('bcrypt')

module.exports.register = async (req, res, next) => {
  try {
    const { username, email, password } = req.body
    const usernameCheck = await userModel.findOne({ username })
    if (usernameCheck) {
      return res.json({ msg: '该用户名已被使用', status: false })
    }
    const emailCheck = await userModel.findOne({ email })
    if (emailCheck) {
      return res.json({ msg: '该邮箱已被使用', status: false })
    }
    const hashedPassword = await bcrypt.hash(password, 10)
    const user = await userModel.create({
      email,
      username,
      password: hashedPassword
    })
    user.password = null
    delete user.password
    return res.json({ status: true, user })
  } catch (ex) {
    next(ex)
  }
}

module.exports.login = async (req, res, next) => {
  try {
    const { username, password } = req.body
    const user = await userModel.findOne({ username })
    if (!user) {
      return res.json({ msg: '用户名或密码错误，请重新输入', status: false })
    }
    const isPasswordValid = await bcrypt.compare(password, user.password)
    if (!isPasswordValid) {
      return res.json({ msg: '用户名或密码错误，请重新输入', status: false })
    }
    user.password = null
    delete user.password
    return res.json({ status: true, user })
  } catch (ex) {
    next(ex)
  }
}

module.exports.setAvatar = async (req, res, next) => {
  try {
    const userId = req.params.id
    const avatarImage = req.body.image
    const userData = await userModel.findByIdAndUpdate(userId, {
      isAvatarImageSet: true,
      avatarImage
    })
    return res.json({ isSet: true, image: avatarImage })
  } catch (ex) {
    next(ex)
  }
}

module.exports.getAllUsers = async (req, res, next) => {
  try {
    const users = await userModel.find({ _id: { $ne: req.params.id } }).select(['email', 'username', 'avatarImage', '_id'])
    return res.json(users)
  } catch (ex) {
    next(ex)
  }
}
